//
//  NewsTableViewController.m
//  Cunli
//
//  Created by lilubin on 15/6/10.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "NewsTableViewController.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "NewsModel_yy.h"
#import "NewsCell.h"
#import "UIImageView+WebCache.h"
#import "NewDetailController.h"
#import "MJRefresh.h"
#import "HMBannerView.h"
#import "Config.h"
#import "MBProgressHUD.h"
#import "ScrollLabelView.h"
#import "TongZhiDetailViewController.h"
#import "ActivityPopView.h"
#import "ActivityWebVC.h"
#import "FluxPresentView.h"
#import "UMessage.h"
#import "AFNetworking.h"
#import "DeviceInfoClass.h"

#define KCLLOGINCHANGE @"myloginchange"
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define pageSize 6
#define APP_URL @"http://itunes.apple.com/lookup?id=1024868113"

static NSString *kNewsCellID = @"NewsCell";

@interface NewsTableViewController () <HMBannerViewDelegate, ScrollLabelViewDelegate, UIAlertViewDelegate>
{
    NSMutableArray *_datasArray; //存放newsModel的数组
    UIPageControl *_pageControl; //头视图中的指示control
    //    UIScrollView *_scrollView;   //头视图中的scrollView
    //    NSUInteger _scrollToIndex;   //滚动到第几张图片
    //    NSTimer *_imgTimer;          //图片循环的定时器
    NSArray *_bannerPositions;   //存放banner的位置
    NSArray *_bannerDatasArray;  //存放banner的数据，字典形式的数组
    NSArray *_noteDatasArray;    //存放note的数据
    BOOL _firstAppear;
}

@property (nonatomic, strong) HMBannerView *bannerView;

@end

@implementation NewsTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.rowHeight = 90;
    [self reloadDataToNew:YES];
    [self registerNewsCell];
    [self addRefreshAttribute];
    _firstAppear = YES;
    /*
    if (_newsType == NewsListTypeOutside) {
        [self checkAppVersion];
        if ([Config getLogintimes].intValue < 4) //第一次登陆，执行赠送流量
        {
            [self fluxPresentAction];
        }
        else
        {
            [self loadActivityData];
        }
    }
     */
    self.tableView.separatorColor = [UIColor colorWithHexString:TableViewSeperateColorValue];
    NSArray *areaidsArray = [[Config getOwnAreaids] componentsSeparatedByString:@","];
    [UMessage addTag:areaidsArray response:^(id responseObject, NSInteger remain, NSError *error) {
        //        NSLog(@"添加APSN失败:%@", error.userInfo);
    }];
//    [self loadStartImage];

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSLog(@"did appear");
    if (_newsType == NewsListTypeOutside && _firstAppear) {
        [self checkAppVersion];
        if ([Config getLogintimes].intValue == 1) //第一次登陆，执行赠送流量
        {
            [self fluxPresentAction];
        }
        else
        {
            [self loadActivityData];
        }
    }
}

- (void)initGlobalParams
{
    _datasArray = [NSMutableArray arrayWithCapacity:6];
    _bannerPositions = @[@"news_index_banner", @"news_wm_banner", @"news_zw_banner", @"news_sb_banner"];
    _bannerDatasArray = [NSArray array];
    _noteDatasArray = [NSArray array];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
 - (void)checkAppVersion
 {
 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
 [manager POST:APP_URL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
 //获得appstore的版本号
 NSLog(@"Check_app_version success:%@", responseObject);
 NSArray *appStoreArray = [responseObject objectForKey:@"results"];
 NSDictionary *appStoreDic = appStoreArray[0];
 NSString *appStoreVersion = [appStoreDic objectForKey:@"version"];
 
 //获取本地的版本号
 NSDictionary *localDic = [[NSBundle mainBundle] infoDictionary];
 NSString *localVersion = [localDic objectForKey:@"CFBundleShortVersionString"];
 
 NSLog(@"appStore version:%@, local version:%@", appStoreVersion,localVersion);
 
 if (![appStoreVersion isEqualToString:localVersion]) {
 UIAlertView *versionAlertView = [[UIAlertView alloc] initWithTitle:@"版本更新提示" message:@"发现新版本，前往更新" delegate:self cancelButtonTitle:@"忽略" otherButtonTitles:@"前往更新", nil];
 [versionAlertView show];
 }
 
 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
 NSLog(@"Check_app_version failed:%@", error);
 }];
 }
 */

- (void)checkAppVersion
{
    //    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:3];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
//    [CheckParams setObject:[Login curLoginBaseUser].userid forKey:@"userid"];

    
    NSDictionary *localDic = [[NSBundle mainBundle] infoDictionary];
    NSString *localVersion = [localDic objectForKey:@"CFBundleShortVersionString"];
    NSString *vlocalVersion = [NSString stringWithFormat:@"V%@", localVersion];
    
    [CheckParams setObject:vlocalVersion forKey:@"version"];
    [CheckParams setObject:@"2" forKey:@"type"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
//  NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Login curLoginBaseUser].usersession];

    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:@"app_version.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        NSLog(@"Check version result:%@", result);
        if ([result[@"response"] isEqualToString:@"app_version"]) {
            if (result[@"versioninfo"] != nil) {
                NSDictionary *versioninfo = result[@"versioninfo"];
                NSString *latestVersion = versioninfo[@"version"];
                
                if (![latestVersion isEqualToString:vlocalVersion]) {
                    UIAlertView *versionAlertView = [[UIAlertView alloc] initWithTitle:@"版本更新提示" message:@"发现新版本，前往更新" delegate:self cancelButtonTitle:@"忽略" otherButtonTitles:@"前往更新", nil];
                    [versionAlertView show];
                }
            }
        }
    } failureAction:^{
//        NSLog(@"Check version failure");
    }];
}

#pragma mark - versionAlert delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        return;
    }
    else
    {
        //        NSLog(@"更新");
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/cun-li-yi-dong-hu-lian-wang/id1024868113?mt=8"]];
    }
}

- (void)fluxPresentAction
{
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:2];
    
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    
//    [CheckParams setObject:[Login curLoginBaseUser].userid forKey:@"userid"];
//    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Login curLoginBaseUser].usersession];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:@"give_flux.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        NSLog(@"FluxResult:%@", result);
        NSDictionary *dataDic = result[@"data"];
        if ([result[@"response"] isEqualToString:@"give_flux"]) {
            [weakSelf performSelector:@selector(popFluxView:) withObject:dataDic[@"amount"] afterDelay:0.5];
        }
        else
        {
            /*
             if ([result[@"response"] isEqualToString:@"error"]) {
             NSDictionary *dic = result[@"error"];
             [Config showHUDWithText:dic[@"text"] andImage:@"error"];
             }
             */
            [weakSelf loadActivityData];
        }
    } failureAction:^{
        //        [Config showHUDWithText:@"流量赠送失败" andImage:@"error"];
        [weakSelf loadActivityData];
    }];
}

/*
- (void)loadStartImage
{
    [MyDataService requestURL:@"app_start_banner.php" httpMethod:@"POST" params:nil fileDatas:nil complection:^(id result) {
        NSLog(@">>> APPSTART RESULT:%@>>>", result);
        if ([result[@"response"] isEqualToString:@"app_start_banner"]) {
            NSDictionary *dataDic = result[@"data"];
            
            _imageUrl = dataDic[@"pic"];
            dispatch_async(dispatch_get_main_queue(), ^{
                [bgImgView setImageWithURL:[NSURL URLWithString:_imageUrl] placeholderImage:[UIImage imageNamed:@"Default"]];
            });
            
        }
    } failureAction:^{
        NSLog(@"app_start_banner.php request failed");
    }];
}
*/
- (void)addRefreshAttribute
{
    __weak typeof(self) weakSelf = self;
    
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:YES]; //刷新
    }];
    
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:NO]; //加载更多
    }];
    
    //    [self.tableView.legendHeader beginRefreshing];
}

- (void)createBannerView
{
    
    CGFloat headerHeight = 160;
    NSArray *heightArray = @[@160, @160, @188, @207];
    NSNumber *heightNumber = heightArray[[DeviceInfoClass getCurrentDeviceDetailVersion]];
    headerHeight = heightNumber.floatValue;
    
    if (_bannerDatasArray.count != 0) {
        if (self.bannerView != nil)
        {
            [self.bannerView reloadBannerWithData:_bannerDatasArray];
        }
        else
        {
            self.bannerView = [[HMBannerView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, headerHeight) scrollDirection:ScrollDirectionLandscape images:_bannerDatasArray];
            
            [self.bannerView setRollingDelayTime:4.0];
            [self.bannerView setDelegate:self];
            [self.bannerView setPageControlStyle:PageStyle_Right];
            [self.bannerView startDownloadImage];
            //[self.m_BannerView showClose:YES];
        }
        self.tableView.tableHeaderView = self.bannerView;
    }
}

//注册tableViewCell
- (void)registerNewsCell
{
    UINib *nib = [UINib nibWithNibName:@"NewsCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kNewsCellID];
}

//初始化该控制器
- (instancetype)initWithNewsListType:(NewsListType)type
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {
        _newsType = type;
        [self initGlobalParams];
        [self reloadBannerData];
        /*
        if (_newsType == NewsListTypeOutside) {
            [self reloadNotificationData];
        }
         */
    }
    return self;
}

- (void)loadActivityData
{
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:2];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:[Config getOwnAreaids] forKey:@"areaids"];
    
//    [CheckParams setObject:[Login curLoginBaseUser].userid forKey:@"userid"];
//    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Login curLoginBaseUser].usersession];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:@"active.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        NSLog(@"activityResult:%@", result);
        
        if ([result[@"response"] isEqualToString:@"active_info"])
        {
            NSDictionary *dataDic = result[@"data"];
            if(dataDic.count == 0)
            {
                return;
            }
            //            else
            //            {
            if ([[NSUserDefaults standardUserDefaults] objectForKey:@"activityIDs"] != nil)
            {
                NSMutableArray *idArray = [NSMutableArray arrayWithCapacity:1];
                NSArray *oldArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"activityIDs"];
                idArray = [NSMutableArray arrayWithArray:oldArray];
                
                for(NSString *actId in oldArray)
                {
                    if ([actId isEqualToString:dataDic[@"act_id"]])
                    {
#pragma - mark  为调试，隐藏掉这一行
                        return;
                    }
                }
                
                [weakSelf performSelector:@selector(popActivityView:) withObject:dataDic afterDelay:0.5];
                [idArray addObject:dataDic[@"act_id"]];
                [[NSUserDefaults standardUserDefaults] setObject:idArray forKey:@"activityIDs"];
            }
            else
            {
                NSMutableArray *idArray = [NSMutableArray arrayWithCapacity:1];
                [weakSelf performSelector:@selector(popActivityView:) withObject:dataDic afterDelay:0.5];
                [idArray addObject:dataDic[@"act_id"]];
                [[NSUserDefaults standardUserDefaults] setObject:idArray forKey:@"activityIDs"];
                //                }
            }
        }
        
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
    }];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _datasArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}
/*
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (_newsType == NewsListTypeOutside && _noteDatasArray.count != 0) {
        ScrollLabelView *_labelView = [[ScrollLabelView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 26) scrollDirection:LabelScrollDirectionPortait images:_noteDatasArray];
        [_labelView setBackgroundColor:[UIColor whiteColor]];
        
        _labelView.delegate = self;
        [_labelView setRollingDelayTime:8];
        [_labelView startDownloadImage];
        [_labelView startRolling];
//        return _labelView;
    }
    return nil;
}
 */

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_newsType == NewsListTypeOutside) {
        return 1; //原来是26
    }
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:kNewsCellID forIndexPath:indexPath];
    cell.newsModel = _datasArray[indexPath.row];
    return cell;
}

//将cell的高度固定为120
/*
 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 {
 return 90;
 }
 */

//进入新闻的详情界面只需要传itemid的值即可
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
#pragma - mark  测试活动弹出视图
    NewDetailController *newDetailVC = [[NewDetailController alloc] init];
    NewsModel_yy *newModel2 = _datasArray[indexPath.row];
    newDetailVC.itemID = newModel2.itemid;
    newDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:newDetailVC animated:YES];
}


- (void)popActivityView:(NSDictionary *)resultDic
{
    NSLog(@"popActivityViewDic:%@", resultDic);
    ActivityPopView *popView = [[ActivityPopView alloc] initWithFrame:[self topView].bounds];
    popView.picUrl = resultDic[@"thumb"];
    popView.tag = 2022;
    popView.closeClicked = ^{
        [self closeAction];
    };
    popView.jumpToActivityClicked = ^{
        [self jumpToActivity:resultDic[@"act_id"] activityUrl:resultDic[@"url"]];
    };
    
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    [window addSubview:popView];
    popView.alpha = 0.0f;
    
    [UIView animateWithDuration:0.5 delay:0.5 options:UIViewAnimationOptionCurveEaseIn animations:^{
        popView.alpha = 1.0f;
    } completion:^(BOOL finished) {
        
    }];
}


#pragma mark - 流量赠送界面
- (void)popFluxView:(NSString *)opCode
{
    NSLog(@"popActivityViewDic:%@", opCode);
    FluxPresentView *popView = [[FluxPresentView alloc] initWithFrame:[self topView].bounds];
    popView.opCode = [opCode substringToIndex:1];
    popView.tag = 3022;
    popView.closeClicked = ^{
        [self closeActionFlux];
    };
    popView.jumpToActivityClicked = ^{
        [self closeActionFlux];
    };
    
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    [window addSubview:popView];
    popView.alpha = 0.0f;
    
    [UIView animateWithDuration:0.5 delay:0.5 options:UIViewAnimationOptionCurveEaseIn animations:^{
        popView.alpha = 1.0f;
    } completion:^(BOOL finished) {
        
    }];
}

- (void)closeActionFlux
{
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    FluxPresentView *activityView = (FluxPresentView *)[window viewWithTag:3022];
    [activityView removeFromSuperview];
    [self loadActivityData];
}


-(UIView*)topView {
    UIViewController *recentView = self;
    while (recentView.parentViewController != nil) {
        recentView = recentView.parentViewController;
    }
    return recentView.view;
}

- (void)jumpToActivity:(NSString *)activityId activityUrl:(NSString *)activityUrl
{
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    ActivityPopView *activityView = (ActivityPopView *)[window viewWithTag:2022];
    if (activityView != nil)
    {
        [activityView removeFromSuperview];
    }
    ActivityWebVC *activityVC = [[ActivityWebVC alloc] init];
    activityVC.hidesBottomBarWhenPushed = YES;
    activityVC.activityId = activityId;
    activityVC.activityUrl = activityUrl;
    [self.navigationController pushViewController:activityVC animated:YES];
}

- (void)closeAction
{
    NSLog(@"Close action");
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    ActivityPopView *activityView = (ActivityPopView *)[window viewWithTag:2022];
    [activityView removeFromSuperview];
}

- (void)pushToActivityDetailVC
{
    UIViewController *detailVC = [[UIViewController alloc] init];
    detailVC.view.backgroundColor = [UIColor blueColor];
    [self.navigationController pushViewController:detailVC animated:YES];
}

//加载数据
/*刷新or加载更多函数
 *@new
 *yes:刷新
 *no:加载更多
 */
- (void)reloadDataToNew:(BOOL)new
{
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:5];
    NSString *typeStr = [NSString stringWithFormat:@"%d", _newsType];
    
    NSUInteger page = 1;
    if (!new)  // new = NO 设置page
    {
        page = _datasArray.count/pageSize + 1; //根据当前数据数组中的数据量来判断应该加载第几页
    }
    
    NSString *pageStr = [NSString stringWithFormat:@"%lu", page];
    
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
//    [CheckParams setObject:[Login curLoginBaseUser].userid forKey:@"userid"];
    [CheckParams setObject:typeStr forKey:@"type"];
    [CheckParams setObject:pageStr forKey:@"page"];
    [CheckParams setObject:@"6" forKey:@"pagesize"];
    [CheckParams setObject:[Config getOwnAreaids] forKey:@"areaids"];
//    [CheckParams setObject:[Login curLoginBaseUser].areaids forKey:@"areaids"];
    [CheckParams setObject:@"time_down" forKey:@"orderby"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
//    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Login curLoginBaseUser].usersession];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"newslist.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        NSString *response = [result objectForKey:@"response"];
        NSLog(@"news result:%@", result);
        if ([response isEqualToString:@"news_list"]) {
            NSDictionary *newslistDic = result[@"newslist"];
            NSArray *newsList = newslistDic[@"list"];
            NSInteger totalCount = [newslistDic[@"totalcount"] integerValue];
            /*
             *思路：判断是否是刷新
             *是：移除dataArray中的数据，重新加载第一页
             *否：加载下一页的数据，并且拼接到已存在的数据数组中
             */
            if (new) {
                if (_datasArray.count != 0) {
                    [_datasArray removeAllObjects]; //刷新时，将已有数据清除，加载最新数据
                }
                else
                {
                    if (newsList.count == 0) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.tableView.legendHeader endRefreshing];
                        });
                    }
                }
            }
            if (totalCount == _datasArray.count) {
                if (totalCount != 0) {
                    [Config showHUDWithText:@"没有更多数据" andImage:@"done"];
                }
                [self.tableView.legendFooter setState:MJRefreshFooterStateNoMoreData];
            }
            else
            {
                for(NSDictionary *dataDic in newsList)
                {
                    //                    NewsModel *newModel = [[NewsModel alloc] initWithDic:dataDic];
                    NewsModel_yy *newModel = [NewsModel_yy yy_modelWithJSON:dataDic];
                    [_datasArray addObject:newModel];
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [self.tableView.legendHeader endRefreshing];
                    [self.tableView.legendFooter endRefreshing];
                    [self.tableView reloadData];
                });
            }
            
        }
        
        if ([response isEqualToString:@"error"]) {
            NSDictionary *errorDic = [result objectForKey:@"error"];
            NSString *text = errorDic[@"text"];
            [Config showHUDWithText:text andImage:@"error"];
        }
        
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
        [self.tableView.legendHeader endRefreshing];
        [self.tableView.legendFooter endRefreshing];
        
    }];
    
}

//加载广告栏的数据
- (void)reloadBannerData
{
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:5];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
//    [CheckParams setObject:[Login curLoginBaseUser].userid forKey:@"userid"];
    [CheckParams setObject:@"5" forKey:@"type"];
    [CheckParams setObject:[Config getOwnAreaids] forKey:@"areaids"];
//    [CheckParams setObject:[Login curLoginBaseUser].areaids forKey:@"areaids"];
    if (_newsType == NewsListTypeCountryTwitter) {
        [CheckParams setObject:_bannerPositions[0] forKey:@"position"];
    }else
    {
        [CheckParams setObject:_bannerPositions[_newsType] forKey:@"position"];
    }
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
//    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Login curLoginBaseUser].usersession];

    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:@"ads.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"Banner datas:%@", result);
        if (![result[@"response"] isEqualToString:@"error"])
        {
            _bannerDatasArray = result[@"adslist"];
            [self createBannerView];
        }
        
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
    }];
}

//加载通知通告栏数据
/*
- (void)reloadNotificationData
{
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:3];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:[Config getOwnAreaids] forKey:@"areaids"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:@"gd_note.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        //        NSLog(@"GD_NOTE  result:%@", result);
        if ([result[@"response"] isEqualToString:@"gd_note"]) {
            _noteDatasArray = result[@"list"];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
            });
        }
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
    }];
}
 */

#pragma mark - <UIScrollViewDelegate>
/*
 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
 {
 if (scrollView.tag == 100) {
 CGFloat xOffset = scrollView.contentOffset.x;
 
 _pageControl.currentPage = xOffset / kScreenWidth;
 }
 }*/

//视图消失时，取消定时器
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    _firstAppear = NO;
}


#pragma mark HMBannerViewDelegate

- (void)imageCachedDidFinish:(HMBannerView *)bannerView
{
    [self.view addSubview:bannerView];
    [bannerView startRolling];
}

- (void)bannerView:(HMBannerView *)bannerView didSelectImageView:(NSInteger)index withData:(NSDictionary *)bannerData
{
    if (bannerData != nil) {
        if ([bannerData[@"type"] integerValue] == 1)
        {
            NewDetailController *newDetailVC = [[NewDetailController alloc] init];
            newDetailVC.itemID = bannerData[@"atc_itemid"];
            newDetailVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:newDetailVC animated:YES];
        }
        else if([bannerData[@"type"] integerValue] == 10)
        {
            [self jumpToActivity:bannerData[@"atc_itemid"] activityUrl:bannerData[@"imageurl"]];
        }
    }
}

- (void)bannerViewdidClosed:(HMBannerView *)bannerView;
{
    if (bannerView.superview)
    {
        [bannerView removeFromSuperview];
    }
}

#pragma mark - ScrollViewDelegate
/*
- (void)labelView:(ScrollLabelView *)labelView didSelectlabelView:(NSInteger)index withData:(NSDictionary *)labelData
{
    if ([labelData[@"type"] intValue] == 0) {
        return;
    }
    
    TongZhiDetailViewController *tongZhiVC=[[TongZhiDetailViewController alloc]init];
    tongZhiVC.itemid = [labelData[@"itemid"] intValue];
    tongZhiVC.type = [labelData[@"type"] intValue];
    tongZhiVC.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:tongZhiVC animated:YES];
}
*/
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (_bannerView != nil) {
        [_bannerView stopRolling];
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (_bannerView != nil) {
        [_bannerView startRolling];
    }
}

@end
